import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/mine/user_page_logic.dart';
import 'package:ball_lion/entity/expert/subs_article_list_entity.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/entity/match/expert_views_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/expert_api.dart';
import 'package:ball_lion/server/api/home_api.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/home/news_cell.dart';
import 'package:ball_lion/module/home/post_cell.dart';
import 'package:ball_lion/module/expert/items/plan_item.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:ball_lion/widgets/loading/loading_indicator.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class UserPublishList extends StatefulWidget {
  final ListType type;
  final String? userId;
  final String? expertId;
  final String? tag;
  const UserPublishList(this.userId, this.expertId, this.type,
      {super.key, this.tag});

  @override
  State<UserPublishList> createState() => _UserPublishListState();
}

class _UserPublishListState extends State<UserPublishList>
    with AutomaticKeepAliveClientMixin {
  List<dynamic>? list;
  int page = 1;
  int pageSize = 30;
  EasyRefreshController refreshC =
      EasyRefreshController(controlFinishLoad: true);
  late final logic = Get.find<UserPageLogic>(tag: widget.tag);

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: Container(
        color: Colours.greyF7,
        child: EasyRefresh(
            controller: refreshC,
            footer: Styles.refreshFooter(position: IndicatorPosition.locator),
            onRefresh: () async {
              page = 1;
              await getData();
            },
            onLoad: () async {
              await getMore();
            },
            child: LoadingWidget<bool>(
                isLoading: list == null,
                loading: const LoadingIndicator(),
                data: list?.length == 0,
                noData: const NoDataWidget(
                  tip: '暂无发布内容',
                  needScroll: true,
                ),
                child: () => listView())),
      ),
    );
  }

  Widget listView() {
    return CustomScrollView(
      slivers: [
        if ((widget.type == ListType.subscribe) && logic.data?.isIdeaOpen == 1)
          SliverToBoxAdapter(
            child: Container(
              height: 44,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  image: DecorationImage(
                      image:
                          AssetImage(Utils.getImgPath('subscribe_bar_bg.png')),
                      fit: BoxFit.cover)),
              margin: const EdgeInsets.only(top: 8, left: 8, right: 8),
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Row(children: [
                Expanded(
                  child: QsText(logic.data?.ideaContent ?? '',
                      color: Colours.gold6A3313),
                ),
                QsButton(
                    text: logic.data?.isIdeaExpert == 0 ? '去订阅' : '去续期',
                    textStyle: const TextStyle(
                        fontSize: 13, color: Colours.goldFFF0CD),
                    borderRadius: 4,
                    width: 56,
                    height: 24,
                    backgroundColor: Colours.gold6A3313,
                    foregroundColor: Colours.goldFFF0CD,
                    onPressed: () async {
                      await Get.toNamed(Routes.subsPay,
                          arguments: logic.data?.expertId);
                      await logic.getData(isNew: false);
                      update();
                    })
              ]),
            ),
          ),
        SliverList.list(
          key: UniqueKey(),
          children: list
                  ?.where((element) => element != null)
                  .map((e) => cell(e))
                  .toList() ??
              [],
        ),
        const FooterLocator.sliver(),
      ],
    );
  }

  Widget cell(dynamic entity) {
    if (entity is NewsItemEntity) {
      final data = entity;
      if (data.type == 2) {
        return PostCell(
          data,
          isUserPage: true,
          afterRoute: () {
            getData();
          },
        );
      } else {
        return NewsItemCell(
          data,
          inHome: false,
          afterRoute: update,
        );
      }
    } else if (entity is PlanEntity) {
      final data = entity;
      return Styles.card(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
          child: PlanItem(entity: data));
    } else if (entity is ArticleDetail) {
      final data = entity;
      NewsItemEntity news = NewsItemEntity()
        ..pv = '${data.uv}'
        ..title = data.title
        ..summary = data.summary
        ..publishTime = data.publishTime
        ..imgStyle = data.imgType
        ..imgs = data.img
        ..id = data.id
        ..publisherId = data.expertId;

      return NewsItemCell(
        news,
        inHome: true,
        afterRoute: update,
        isSubscribe: true,
      );
    }
    return Container();
  }

  getData() async {
    List? result;
    if (widget.type == ListType.all) {
      result = await HomeApi.getUserAllPublish(page, pageSize,
          userId: widget.userId, expertId: widget.expertId);
    } else if (widget.type == ListType.article ||
        widget.type == ListType.post ||
        widget.type == ListType.video) {
      int publishType = 1;
      if (widget.type == ListType.post) {
        publishType = 2;
      } else if (widget.type == ListType.video) {
        publishType = 3;
      }
      if (widget.userId == null) {
        if (page == 1) list = [];
      } else {
        result = await HomeApi.getUserPublish(
            widget.userId ?? '', publishType, page, pageSize);
      }
    } else if (widget.type == ListType.soccer ||
        widget.type == ListType.basket) {
      int id = widget.type == ListType.soccer ? 1 : 2;
      result = await ExpertApi.getPlanHistory(
          widget.expertId ?? '', id, page, pageSize);
    } else if (widget.type == ListType.subscribe) {
      result = await ExpertApi.getSubsArticleList(
          widget.expertId ?? '', page, pageSize);
    }
    if (result != null) {
      if (page == 1) {
        list = result;
      } else {
        list?.addAll(result);
      }
    }
    if (page == 1) {
      refreshC.resetFooter();
    } else {
      refreshC.finishLoad((list?.length ?? 0) < page * pageSize
          ? IndicatorResult.noMore
          : IndicatorResult.success);
    }
    update();
  }

  getMore() {
    page++;
    getData();
  }

  @override
  bool get wantKeepAlive => true;
}
